package com.sso.auth;

import com.sso.credential.CustomCredential;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.authentication.AuthenticationHandlerExecutionResult;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.MessageDescriptor;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler;
import org.apereo.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类 {@code MyAuthenticationHandler} 自定义账号密码验证逻辑 <br> 自定义账号密码验证逻辑.
 *
 * <p>详细描述
 * <p>
 *
 * @author <a href="mailto:lz2392504@gmail.com">CN華少</a>
 * @see AbstractUsernamePasswordAuthenticationHandler
 * @see UsernamePasswordCredential
 * @since v1.0.0
 */
@Slf4j
@Setter
@Getter
public class MyAuthenticationHandler extends AbstractPreAndPostProcessingAuthenticationHandler {

    public MyAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {
        super(name, servicesManager, principalFactory, order);
    }

    @Override
    protected AuthenticationHandlerExecutionResult doAuthentication(Credential credential) throws GeneralSecurityException, PreventedException {
        CustomCredential customCredential = (CustomCredential) credential;
        // 继承过来的账号密码
        String username = customCredential.getUsername();
        String password = customCredential.getPassword();
        // 定制中的验证码
        String captcha = customCredential.getCaptcha();
        System.out.println("当前验证信息为："+username+"  "+password+"  "+captcha);

        //TODO 省略验证步骤，后续单独讲解

        final List<MessageDescriptor> list = new ArrayList<>();
        return createHandlerResult(credential,this.principalFactory.createPrincipal(username),list);
    }

    @Override
    public boolean preAuthenticate(Credential credential) {
        return super.preAuthenticate(credential);
    }

    @Override
    public AuthenticationHandlerExecutionResult postAuthenticate(Credential credential, AuthenticationHandlerExecutionResult result) {
        return super.postAuthenticate(credential, result);
    }
}
